package cn.com.chengq.dictionary;

import cn.com.chengq.dictionary.spi.Dictionary;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 加载和访问可用服务提供商(SPI).
 * 客户端使用该类，使用字典服务。
 */
public class DictionaryService {
    private static DictionaryService service;
    private ServiceLoader<Dictionary> loader;

    private DictionaryService() {
        System.out.println("Load class: DictionaryService by " + DictionaryService.class.getClassLoader().getClass().getName());
        System.out.println("java.ext.dirs: \n  " + System.getProperties().getProperty("java.ext.dirs"));
        System.out.println("java.class.path: \n  " + System.getProperties().getProperty("java.class.path"));

        loader = ServiceLoader.load(Dictionary.class);
        if (loader.iterator().hasNext()) {
            loader.iterator().forEachRemaining((item) -> {
                System.out.println(item.getClass().getClassLoader().getClass().getName());
                System.out.println(item.getClass().getName());
            });
        }
    }

    public static synchronized DictionaryService getInstance() {
        return service != null ? service : new DictionaryService();
    }

    /**
     * 给客户端提供的字典查询的API接口。
     * @param word
     * @return
     */
    public String getDefinition(String word) {
        String definition = null;


        Iterator<Dictionary> dictionaries = loader.iterator();
        while (definition == null && dictionaries.hasNext()) {
            Dictionary dict = dictionaries.next();
            System.out.println("Searching work from Dictionary:  " + dict.getClass().getName());
            definition = dict.getDefinition(word);
        }

        return definition;
    }
}
